<script setup lang="ts">
import { useAdmin } from "../../../stores/admin";
import { useToken } from "../../../stores/token";
import { ref, inject, type Ref } from "vue";
import type { UploadInstance } from "element-plus";
import { uploadPictureURL, changeAdminAvatar } from "../../../api"; //引入 API 函数
import type { AxiosResponse } from "axios"; //导入 response 类型
import { ElMessage } from "element-plus"; //导入消息框
const adminStore = useAdmin();
const tokenStore = useToken();
//用户头像
const headImage = inject<Ref>("headImage", ref(""));
//图片上传地址
const uploadURL = uploadPictureURL();
//设置图片上传时请求的头
const headers = { jwt: tokenStore.token };
//定义商品上传组件实例
const uploadRef = ref<UploadInstance>();
//上传头像
function submitUpload() {
  uploadRef.value?.submit();
}
//图片上传成功后的回调函数
async function uploadSuccess(response: AxiosResponse) {
  //修改管理员头像
  const res = await changeAdminAvatar({ avatar: response.data.savepath });
  if (res.data.errno == 0) {
    //修改头像成功
    ElMessage.success(res.data.errmsg);
    //设置显示的头像
    headImage.value = response.data.url;
    //设置管理员 stores 中的头像
    adminStore.admin.avatar = response.data.url;
  } else {
    //修改头像失败
    ElMessage.error(res.data.errmsg);
  }
  //清空上传组件的已上传文件列表
  uploadRef.value?.clearFiles();
}
</script>
<template>
  <section class="person_image">
    <div>头像信息</div>
    <div><img :src="headImage" /></div>
    <el-upload
      ref="uploadRef"
      :action="uploadURL"
      :limit="1"
      :headers="headers"
      :data="{ type: 'admin_avatar' }"
      :auto-upload="false"
      :on-success="uploadSuccess"
    >
      <template #trigger>
        <div class="image_btn">
          <el-button type="primary">选择头像</el-button>
        </div>
      </template>
      <template #default>
        <div class="image_btn">
          <el-button type="success" @click="submitUpload">上传头像</el-button>
        </div>
      </template>
      <template #tip>
        <div class="image_txt">限制上传 1 个文件，且旧文件会被新文件覆盖</div>
      </template>
    </el-upload>
  </section>
</template>
<style scoped>
.person_image {
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  width: 30%;
  box-shadow: 0px 0px 5px 5px #e4e7ed;
  margin: 20px;
}
.person_image div:not(:first-child) {
  text-align: center;
  margin: 5px 0px;
}
.person_image > div:first-child {
  font-size: 15px;
  text-indent: 15px;
  line-height: 50px;
  border-bottom: 1px solid #e4e7ed;
}
.person_image img {
  width: 50px;
  height: 50px;
  margin-top: 10px;
}
.person_image .image_txt {
  color: gray;
  font-size: 13px;
}
</style>
